package com.cloud.common.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.common.exception.AppException;
import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * DAO辅助类
 *
 * @author fengwenjin
 */
public class DaoHelper {
    private static final String FIELD_ID = "id";

    /**
     * 设置某个字段排序，排序字段是空则默认按ID降序
     *
     * @param wrapper
     * @param entityClass
     * @param sortField
     * @param isAsc
     */
    public static void setQuerySort(QueryWrapper wrapper, Class entityClass, String sortField, boolean isAsc) {
        // 检查entity的字段是否存在sortField，防止SQL注入
        if (StringUtils.isNotEmpty(sortField) && !existField(entityClass, sortField)) {
            throw new AppException("sortField not exist");
        }

        sortField = StringUtils.isEmpty(sortField) ? FIELD_ID : sortField;
        sortField = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, sortField);
        if (isAsc) {
            wrapper.orderByAsc(sortField);
        } else {
            wrapper.orderByDesc(sortField);
        }
    }

    /**
     * 检查字段是否存在
     *
     * @param entityClass
     * @param fieldName
     * @return boolean
     */
    public static boolean existField(Class entityClass, String fieldName) {
        try {
            Field field = entityClass.getDeclaredField(fieldName);
            return field != null;
        } catch (NoSuchFieldException e) {
            return false;
        }
    }
}
